import re

from utils.es_upload_utils.new_case.my_utils import get_writ, get_file_path


# title = "李玉梅、常石磊民间借贷纠纷民事一审民事判决书"


# original_link: 原始链接, case_number: 案号, case_name: 案件名称, court: 法院,
# region: 所属地区, case_type: 案件类型, case_type_code: 案件类型编码, source: 来源, trial_procedure: 审理程序,
# judgment_date: 裁判日期, publication_date: 公开日期, parties: 当事人, case_reason: 案由, legal_basis: 法律依据, full_text: 全文
def data_generator(original_link, case_number, case_name, court, region, case_type, case_type_code, source,
                   trial_procedure, judgment_date, publication_date, parties, case_reason, legal_basis, full_text):
    # 法律依据处理：换行
    legal_basis = legal_basis.replace('#', '\n')
    # full_text = full_text.replace('\n', '\\n')

    # (2020)皖0103民初14353号2c892e08dcff4e1d85eeadb000141c1c判决书.txt 变成 (2020)皖0103民初14353号
    case_number = case_number.split('号')[0] + '号'

    return {
        "_index": "case_index_1",
        "_source": {
            "original_link": original_link,
            "case_number": case_number,
            "case_name": case_name,
            "court": court,
            "region": region,
            "case_type": case_type,
            "case_type_code": case_type_code,
            "source": source,
            "trial_procedure": trial_procedure,
            "judgment_date": judgment_date,
            "publication_date": publication_date,
            "parties": parties,
            "case_reason": case_reason,
            "legal_basis": legal_basis,
            "full_text": full_text,
        }
    }


def run(upload_file_path,time):
    _, _, case_types = get_writ()

    # case_types = type_map.values()
    case_type_pattern = '|'.join(re.escape(case_type) for case_type in case_types)

    # 正则表达式模式
    pattern_title = f'(?P<案由>{case_type_pattern})|(?P<审理程序>[一二三四五六七八九十]+审)|(?P<文书类型>[判决通知裁决裁定]+书)'
    pattern_law = f'《中华人民共和国[^》]+》(第[^条]+条)(第[^款]+款)?(第[^项]+项)?|《最高人民法院[^》]+》(第[^条]+条)(第[^款]+款)?(第[^项]+项)?'
    pattern_plaintiff = f'原告：[^\uFF0C]+'

    infos_all = get_file_path(upload_file_path)

    for infos in infos_all:
        # print(infos)
        # 文书位置(file_path)、文件名(filename)、案件名(title)、法院(court)、省份(province)、案件类型(case_type)、文书类型(writ_type)、审理程序(procedure)、案由(case_brief)、法律依据(laws)、全文
        province, court, case_type, filename, file_path = infos[0], infos[1], infos[2], infos[3], infos[4]
        # print(infos)

        with open(file_path, 'r') as file:
            lines = file.readlines()
            # if lines:
            # print(lines[0].strip())

        title = lines[0].strip()
        # print(title)
        # 匹配标题
        matches = re.finditer(pattern_title, title)

        flag = True
        # 提取信息
        case_brief, writ_type, procedure = '', '', ''
        for match in matches:
            if match.group('案由') and flag:
                # print(f"案由: {match.group('案由')}")
                case_brief = match.group('案由')
                flag = False  # 案由会存在多次匹配 案由通常靠前 只取第一个
            elif match.group('文书类型'):
                # print(f"文书类型: {match.group('文书类型')}")
                writ_type = match.group('文书类型')
            elif match.group('审理程序'):
                # print(f"审理程序: {match.group('审理程序')}")
                procedure = match.group('审理程序')

        law_group, plaintiff_group = [], []
        for line in lines:
            matches = re.finditer(pattern_law, line.strip())
            for match in matches:
                law_group.append(match.group())
            matches = re.findall(pattern_plaintiff, line.strip())
            for match in matches:
                plaintiff_group.append(match)

        laws = '#'.join(law_group)
        plaintiffs = '#'.join(plaintiff_group)

        # f.write(','.join(
        #     [file_path, filename, court, province, case_type, '', '本地', procedure, '2021/10/08', '2021/10/08', plaintiffs,
        #      case_brief, laws, '"' + ''.join(lines) + '"']) + '\n')

        res = data_generator(original_link='', case_number=filename, case_name=title, court=court, region=province,
                             case_type=case_type, case_type_code='', source='', trial_procedure=procedure,
                             judgment_date=time, publication_date=time, parties=plaintiffs,
                             case_reason=case_brief,
                             legal_basis=laws, full_text=''.join(lines)
                             )
        yield res

# f.close()

# {
#     '原始链接': ,
#     '案号': ,
#     '案件名称': ,
#     '法院': ,
#     '所属地区': ,
#     '案件类型': ,
#     '案件类型编码': ,
#     '来源': ,
#     '审理程序': ,
#     '裁判日期': ,
#     '公开日期': ,
#     '当事人': ,
#     '案由': ,
#     '法律依据': ,
#     '全文': ,
# }
